import Router from "koa-router";
import NexBidRequest from "../models/nex-bid-request";
import RixBidRequest from "../models/rix-bid-request";
import { convertToRixBidRequest,convertToNexBidResponse } from "../utils";
import axios from "axios";
const nexRouter = new Router();

nexRouter.post("/bidrequest", async (ctx) => {
  const bidRequestUrl = process.env.RIX_BID_ENDPOINT_URL || ""
  try {
    const nexBidRequest:NexBidRequest = ctx.request.body as NexBidRequest;
    const rixBidRequest:RixBidRequest = convertToRixBidRequest(nexBidRequest)
    // 构建OpenRTB bidRequest对象
    const bidRequest = rixBidRequest

    // 发送bidRequest请求
    const response = await axios.post(bidRequestUrl, bidRequest, {
      headers: {
        'Content-Type': 'application/json',
        'timeout': 250,
      },
    });

    // 获取bidResponse响应
    const bidResponse = response.data;

    if (bidResponse && response.status === 200) {
      const bidResponse = convertToNexBidResponse();
      // 设置响应头，指定返回 JSON 格式的数据
      ctx.set("Content-Type", "application/json");
      ctx.body = JSON.stringify(bidResponse);
    } else {
      // 没有有效的bidResponse或状态码不为200时，返回204状态码，并且不返回内容
      ctx.body = '';
      ctx.status = 204;
    }
  } catch (error) {
    console.log('出错了',error)
    // 返回适当的错误响应
    ctx.status = 204; // Bad Request
    ctx.body = "";
  }
});

export default nexRouter;
